<?php

require_once 'core/abstract.db.php';

class index extends db {
	
	public $contentsPage	= array();
	public $mainPage		= array();
	
	public function countCharacterForAccount($aid)
	{
		$this -> open();
		$recordSet = $this -> query("SELECT COUNT(character_id) AS character_for_account FROM characters WHERE account_id = {$aid}") -> fetch();
		return $recordSet;
	}
	
	public function checkLastPassord($aid)
	{
		$this -> open();
		return $d = $this -> query("SELECT COUNT(character_id) AS character_for_account FROM characters WHERE account_id = {$aid}") -> fetch();
	}
		
	public function getContent($page) {
		$this -> open();
		$this -> query("SELECT title_page, content_page FROM pages WHERE name_page = '{$page}'");
		
		if($this -> numrows > 0)
		{
			$rd = $this -> fetch();
				$titlePage = $rd['title_page'];
				$contentPage = $rd['content_page'];
		} else {
			$titlePage = 'Pagina non trovata - Errore';
			$contentPage = 'La pagina che si cerca di visualizzare non è stata trovata nel sistema.';
		}
		
		return $this -> contentsPage = array('title' => $titlePage, 'content' => $contentPage);
		
	}
	
	public function login ($email = '', $pass = '') {
	
		$pass_encode = $this -> data_crypt($_POST['pass']);
	
		$this -> open();
			$this -> query("SELECT accounts.account_id account_id, accounts.account_email account_email, accounts.account_pass account_pass, accounts.account_register account_register, accounts.account_lastpass account_lastpass, accounts.account_active account_active, accounts.account_founder account_founder, accounts.account_admin account_admin, accounts.account_master account_master, accounts.account_programmer account_programmer, accounts.account_name account_name,
							IF(TIMESTAMP(banned.ban_enddate) > TIMESTAMP(NOW()), 1, 0) AS ban_check, banned.ban_enddate ban_enddate
							FROM accounts 
								LEFT JOIN banned ON accounts.account_id = banned.account_id
							WHERE account_email = '$email' AND account_pass = '$pass_encode';");
		if($this -> numrows > 0)
		{
			$data = $this -> fetch();
						
			if($data['ban_check'] == 0)
			{
				session_destroy();
				
				session_start();
				
				$_SESSION['aid'] = $data['account_id'];
				$_SESSION['afounder'] = $data['account_founder'];
				$_SESSION['aadmin'] = $data['account_admin'];
				$_SESSION['amaster'] = $data['account_master'];
				$_SESSION['aprogrammer'] = $data['account_programmer'];
				$_SESSION['aname'] = $data['account_name'];
				$_SESSION['abanned'] = $data['ban_check'];
				setcookie('alastpass', $data['account_lastpass']);
				setcookie('aemail', $data['account_email']);
								
				return TRUE;
			} else {
				echo "Il tuo account risulta essere bannato fino al: " . date('d/m/Y', strtotime($data['ban_enddate']));
			}			
			
		} else {
			echo FALSE;
		}
	}
	
	public function charlogin($id = '') {
	
		$this -> open();
		$this -> query("SELECT character_id, character_name, character_surname, character_race, character_guild, character_guildrank, character_lasttime, character_loc 
							FROM characters
								WHERE character_id = $id AND account_id = " . $_SESSION['aid'] . ";");
		if($this -> numrows > 0)
		{
			$data = $this -> fetch();
	
				$_SESSION['cid'] = $data['character_id'];
				$_SESSION['cname'] = $data['character_name'];
				$_SESSION['csurname'] = $data['character_surname'];
				$_SESSION['crace'] = $data['character_race'];
				$_SESSION['cguild'] = $data['character_guild'];
				$_SESSION['crank'] = $data['character_guildrank'];
				$_SESSION['lasttime'] = $data['character_lasttime'];
				setcookie('location', $data['character_loc']);
				
				if( ! empty($_SESSION['cid']))
				{
					$this -> query('UPDATE characters SET character_lasttime = NOW() WHERE character_id = ' . $_SESSION['cid']);
				}
				
				if( ! empty($_SESSION['cid']) &&  ! empty($_SESSION['cname']))
					return TRUE;
				else
					return FALSE;
				
		} else {
			echo "Controllare di aver selezionato il personaggio correttamente.";
		}
		
	}
	
	public function createCharacter () {
		if( ! empty($_POST) )
		{
			if($_POST['charSex'] != '')
			{
				$this -> open();
				$this -> query("SELECT character_id FROM characters WHERE character_name = '" . $_POST['charName'] . "' AND character_surname = '" . $_POST['charLastName'] . "' ");
				if($this -> numrows == 0)
				{
					if($this -> countcharacterForAccount($_SESSION['aid']) < 2)
					{
					
						$this -> open();
						$this -> query("INSERT INTO `characters` VALUES (NULL," . $_SESSION['aid'] . ",'" . $_POST['charName'] . "','" . $_POST['charLastName'] . "'," . $_POST['charSex'] . ",1,0,0,1000,NOW(),0,'','','','styles/imgs/no-av.png',0,'img/avy-default.jpg',100,1,0,NOW())");
					
						$this -> open();
						$rd = $this -> query("SELECT character_id charId, character_name charName, character_surname charLastName, character_img charImg FROM characters WHERE character_name = '" . $_POST['charName'] . "' AND character_surname = '" . $_POST['charLastName'] . "'") -> fetch();
							return $rd;
					}
				}
			} else {
				return FALSE;
			}
		}
	
	}
	
	public function characterForAccount($aid)
	{
		$numCharacter = $this -> countCharacterForAccount($aid);

		if($numCharacter['character_for_account'] < 2)
		{
			$data['newCharacter'] = '<p><a href="#charReg"role="button"class="btn"data-toggle="modal">Crea un nuovo personaggio</a></p><div id="charReg"class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="ForgotLabel"aria-hidden="true"><div class="modal-header"><button type="button"class="close"data-dismiss="modal"aria-hidden="true">×</button><h3 id="forgotLabel">Crea un nuovo personaggio</h3></div><div class="modal-body text-left"><p class="alert alert-info"><small>Qui potrai creare il tuo personaggio,ti ricordiamo che dovrai scegliere un nome consono all\'ambientazione e non dovrà essere volgare o di persone realmente esistenti.
									<br />
									Inoltre, se non l\'hai già fatto,ti consigliamo di prendere visione del regolamento e delle norme corpontamentali civili.</small></p><form id="createCharacter"method="post"><fieldset><label for="charName">Nome</label><input id="charName"name="charName"type="text"required/><label for="charLastName">Cognome</label><input id="charLastName"name="charLastName"type="text"required/><div class="control-group"><div class="controls"><label class="radio inline"><input type="radio"id="charSex1"name="charSex"value="0">Maschio</label><label class="radio inline"><input type="radio"id="charSex2"name="charSex"value="1">Femmina</label></div></div><p><p class="alert"><small><strong>Attenzione</strong> Una volta creato un personaggio non è più possibile cancellarlo.</small></p><input class="btn btn-success"id="submitCreateCharacter"type="submit"value="Crea Personaggio"/></p></fieldset></form></div></div>';
		} else {
			$data['newCharacter'] = '';
		}
		
		if((strtotime($_COOKIE['alastpass']) + (3600 * 24 * 90)) < time())
		{
			$data['changePassword'] = '<div id="alertChPass"class="alert-info"><button type="button"class="close"data-dismiss="alert">&times;</button><h4>Informazione</h4>La tua password sta per scadere,ti ricordiamo cheèil momento di cambiarla.<form action="#"method="post"><fieldset><legend>Cambia la password</legend><label for="passwordNew">Nuova Password</label><input type="password"id="passwordNew"required/><label for="passwordNewC">Conferma la Nuova Password</label><input type="password"id="passwordNewC"required/><p><input class="btn btn-primary"type="submit"value="Conferma"/></p></fieldset></form></div></div>';
		} else {
			$data['changePassword'] = '';
		}
		
		$this -> open();
		$this -> query("SELECT character_id, character_name, character_surname, character_sex, character_img FROM characters WHERE account_id = {$aid}");
		$thumbCharacter = '';
		while($rd = $this -> fetch())
		{
			 $thumbCharacter .= '<li class="span5 offset1"><div class="thumbnail">
									<img src="' . $rd['character_img'] . '" width="300" height="200">
									<div class="caption">
										<h5>' . $rd['character_name'] . ' ' . $rd['character_surname'] . '</h5>
										<form action="charlogin.php" method="post" target="_blank">
										<p><input type="hidden" name="charId" value="' . $rd['character_id'] . '" />
										<button class="btn btn-success">Entra</button></p>
										</form>
									</div>
								</div></li>';
		}
		$data['thumbCharacter'] = $thumbCharacter;
		
		return $data;

	}
	
	
}

?>